package service

import (
	"fmt"
	"mime/multipart"
	"tiktok2023/model"
	"tiktok2023/store"
	"tiktok2023/store/aliyun"
	"time"

	"github.com/gin-gonic/gin"
)

var (
	uploader store.Uploader
)

type PublishService struct {
}

type PublishResponse struct {
	StatusCode int    `json:"status_code"`
	StatusMsg  string `json:"status_msg"`
}

func (p PublishService) HandlePublish(c *gin.Context) (resp *PublishResponse, err error) {

	var request struct {
		Data  *multipart.FileHeader `json:"data"   form:"data" `
		Token string                `json:"token"  form:"token" `
		Title string                `json:"title" form:"title" `
	}

	if err := c.ShouldBind(&request); err != nil {
		// 处理参数绑定错误
		return nil, err
	}

	userId := c.GetUint64("userId")
	title := request.Title
	fmt.Printf("文件标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题：%v\n", userId)

	// 1、获取上传的文件
	file, err := c.FormFile("data")
	if err != nil {
		// 处理文件上传错误
		return &PublishResponse{
			StatusCode: 1,
			StatusMsg:  "文件解析出错",
		}, err
	}

	// 2、创建阿里云代理
	ali, err := aliyun.NewDefaultNewAliOssStore()
	if err != nil {
		// 创建 OSS client 错误处理
		return &PublishResponse{
			StatusCode: 1,
			StatusMsg:  "连接阿里云失败",
		}, err
	}
	uploader = ali
	BucketName := ""

	// 3、上传文件
	downloadURL, err := uploader.Upload(BucketName, "exampledir/"+file.Filename, file)
	if err != nil {
		// 创建 OSS client 错误处理
		return &PublishResponse{
			StatusCode: 1,
			StatusMsg:  "上传过程出错了",
		}, err
	}

	// 使用阿里云视频处理功能，从视频中截取封面图像
	// coverURL, err := generateCoverFromVideo(videoDownloadURL)
	// if err != nil {
	// 	// 处理截取封面失败的情况
	// 	coverURL = "默认封面URL" // 设置一个默认的封面图像URL
	// }

	// 4、存入数据库
	fileInfo := model.VideosTable{
		AuthorId:    c.GetUint64("userId"),
		PlayUrl:     downloadURL,
		CoverUrl:    "https://assets.1024code.com/img/cover/2023081036-r7Xl7LkKpnED4PD2.png?imageView2/format/webp/q/75/2/w/384",
		Title:       title,
		PublishTime: time.Now().Unix(),
	}

	//存入数据库
	if err := model.Db.Create(&fileInfo).Error; err != nil {
		return nil, err
	}

	return &PublishResponse{
		StatusCode: 0,
		StatusMsg:  "投稿成功",
	}, err
}

type PublishListResponse struct {
	model.Response
	VideoList []model.Video `json:"video_list"`
}

func (p PublishService) HandlePublishList(c *gin.Context) (*PublishListResponse, error) {
	userId := c.GetUint64("userId")
	user := model.TableUser{}
	if err := model.Db.Where("id = ?", userId).First(&user).Error; err != nil {
		return nil, err
	}
	vedios := []model.Video{}
	if err := model.Db.Where("author_id = ?", userId).Find(&vedios).Error; err != nil {
		return nil, err
	}
	for i, _ := range vedios {
		vedios[i].Author = user
		// 判断用户是否登录了
		token := c.Query("token")
		if len(token) != 0 {
			// 判断是否存在
			userId := c.GetUint64("userId")
			if err := model.Db.Where("user_id = ? AND video_id = ? AND cancel = 0", userId, vedios[i].Id).First(&model.LikesTable{}).Error; err == nil {
				vedios[i].IsFavorite = true
			}
		}
		// 再查询该视频的点赞数和评论数
		if err := model.Db.Model(&model.LikesTable{}).Where("video_id = ? AND cancel = 0", vedios[i].Id).Count(&vedios[i].FavoriteCount).Error; err != nil {
			return nil, err
		}
		if err := model.Db.Model(&model.CommentTable{}).Where("video_id = ? AND cancel = 0", vedios[i].Id).Count(&vedios[i].CommentCount).Error; err != nil {
			return nil, err
		}
	}
	res := PublishListResponse{
		Response: model.Response{
			StatusCode: 0,
		},
		VideoList: vedios,
	}
	return &res, nil
}
